package com.nami.logic.thread;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 描述：
 *
 * @Author: lbc
 * @Date: 2023-07-27 11:01
 * @email: 594599620@qq.com
 * @Description: keep coding
 */
@Slf4j
public class ThreadPoolManager {

    /**
     * TODO 需要验证 是否会出现线程阻塞，容易出现cpu 100%  mem 100%
     * 线程池
     */
    public static final ExecutorService COMMON_POOL = new ThreadPoolExecutor(10, 20, 10L, TimeUnit.SECONDS
        , new LinkedBlockingDeque<>(100)
        , ThreadFactoryBuilder.create().setNamePrefix("nami-thread-pool").setDaemon(true).setUncaughtExceptionHandler(((thread, throwable) -> log.error("ThreadPool {} got exception", thread, throwable))).build()
        , new ThreadPoolExecutor.AbortPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            log.warn("[nami-thread-pool] 线程爆炸了, 当前运行线程总数：{}，活动线程数：{}。等待队列已满，等待运行任务数：{}",
                e.getPoolSize(),
                e.getActiveCount(),
                e.getQueue().size());
        }
    });

    /**
     * c2g
     */
    public static final ExecutorService GDISPATCHERS = new ThreadPoolExecutor(5, 10, 10L, TimeUnit.SECONDS
        , new LinkedBlockingDeque<>(50)
        , ThreadFactoryBuilder.create().setNamePrefix("DISPATCHER_G_").setDaemon(true).setUncaughtExceptionHandler(((thread, throwable) -> log.error("ThreadPool {} got exception", thread, throwable))).build()
        , new ThreadPoolExecutor.CallerRunsPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            log.warn("[DISPATCHER-G] 线程爆炸了, 当前运行线程总数：{}，活动线程数：{}。等待队列已满，等待运行任务数：{}",
                e.getPoolSize(),
                e.getActiveCount(),
                e.getQueue().size());
        }
    });

    /**
     * c2c
     */
    public static final ExecutorService PDISPATCHERS = new ThreadPoolExecutor(10, 20, 10L, TimeUnit.SECONDS
        , new LinkedBlockingDeque<>(100)
        , ThreadFactoryBuilder.create().setNamePrefix("DISPATCHER_P_").setDaemon(true).setUncaughtExceptionHandler(((thread, throwable) -> log.error("ThreadPool {} got exception", thread, throwable))).build()
        , new ThreadPoolExecutor.CallerRunsPolicy() {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            log.warn("[DISPATCHER-P] 线程爆炸了, 当前运行线程总数：{}，活动线程数：{}。等待队列已满，等待运行任务数：{}",
                e.getPoolSize(),
                e.getActiveCount(),
                e.getQueue().size());
        }
    });


}


